package com.symria.framework.util;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * <code>CookieUtils</code> Cookie 工具类，提供了各种服务器对 Cookie 文件的操作方法。
 * <p>
 * <a href="CookieUtils.java.html"><i>查看源代码</i></a>
 * </p>
 * 
 * @author <a href="mailto:authormail?Subject=CookieUtils">luo</a>
 * @version 1.0 Sep 22, 2008 11:30:43 PM
 */
public class CookieUtils {

	/**
	 * 测试 Cookie 文件信息是否为空
	 * 
	 * @param request
	 * @return
	 * @author David Dai
	 */
	public static boolean isEmpty(HttpServletRequest request) {
		return (null == request) ? true : false;
	}

	/**
	 * 获取全部 Cookie 文件信息
	 * 
	 * @param request
	 * @return
	 * @author luo
	 */
	public static Cookie[] getAllCookies(HttpServletRequest request) {
		Cookie[] cookies = (null == request) ? null : request.getCookies();
		return cookies;
	}

	/**
	 * 清空客户端 Cookie 文件内容
	 * 
	 * @param request
	 * @param response
	 * @author luo
	 */
	public static void clearCookie(HttpServletRequest request,
			HttpServletResponse response, String userId) throws Exception {
		Cookie[] cookies = request.getCookies();
		try {
			for (int i = 0; i < cookies.length; i++) {
				Cookie cookie = new Cookie(userId, null); // 用户 ID
				cookie.setValue("");
				cookie.setMaxAge(-1); // 最大有效时间
				cookie.setPath("/"); // 根据你创建 cookie 的路径进行填写
				response.addCookie(cookie);
			}
		} catch (Exception e) {
			throw e;
		}
	}
	public static Cookie getCookie(HttpServletRequest request,String cookieName){
		Cookie cookies[]= getAllCookies(request);
		for(Cookie c: cookies){
			if(c.getName().equals(cookieName)){
				return c;
			}
			
		}
		
		return null;
	}
	public static String getCookieValue(Cookie cookie){
		if(null==cookie) return null;
		String value = null;
		try {
			value = (null==cookie)?null:URLDecoder.decode(cookie.getValue(),"utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return value;
	}

}
